<template>
  <el-dialog
    v-model="visible"
    title="新增报告"
    width="660px"
    :close-on-click-modal="false"
    @close="resetDialog"
  >
    <el-form :model="form" label-width="90px" class="generate-form">
      <el-form-item label="报告类型：" class="type-row">
        <el-select v-model="form.reportType" style="width: 120px">
          <el-option label="周报" value="周报" />
          <el-option label="月报" value="月报" />
        </el-select>
      </el-form-item>
      <el-form-item class="upload-row">
        <el-upload
          class="upload-demo custom-upload"
          drag
          :action="uploadFileUrl"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          :file-list="file ? [file] : []"
          accept=".xlsx,.xls"
          :headers="headers"
          ref="uploadRef"
        >
          <div class="upload-inner">
            <el-icon class="upload-icon"><Upload /></el-icon>
            <div class="el-upload__text upload-text">
              点击或将EXCEL文件拖拽到这里上传
            </div>
          </div>
        </el-upload>
        <div v-if="file" class="file-info-bar">
          <el-icon class="file-clip"><Paperclip /></el-icon>
          <span class="file-name">{{ file.name }}</span>
          <el-progress
            :percentage="100"
            status="success"
            style="
              width: 40%;
              margin: 0 8px;
              display: inline-block;
              vertical-align: middle;
            "
          />
          <el-button
            type="text"
            :icon="Close"
            class="file-close"
            @click="handleFileRemove"
          />
        </div>
      </el-form-item>
      <el-form-item label="报告名称：" class="name-row">
        <el-input
          v-model="form.reportName"
          style="width: 360px; height: 100%"
        />
        <!-- <div class="generate-tip">默认为：文件名+报告类型，可以修改</div> -->
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="footer-btns">
        <el-button @click="handleCancel">取消</el-button>
        <el-button :loading="saveLoading" @click="handleSave">暂存</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit"
          >报告生成</el-button
        >
      </div>
    </template>
    <!-- <div class="tip-float">默认为：文件名+报告类型，可以修改</div> -->
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from "vue";
import {
  generateWeekReport,
  generateMonthReport,
  saveReport,
} from "../services";
import { ElMessage } from "element-plus";

const props = defineProps({
  modelValue: Boolean,
  uploadFileUrl: String,
  headers: Object,
  defaultType: { type: String, default: "周报" },
  defaultName: { type: String, default: "" },
});
const emit = defineEmits(["update:modelValue", "save", "submit", "cancel"]);

const visible = ref(false);
const form = reactive({
  reportType: props.defaultType,
  reportName: props.defaultName,
});
const file = ref(null);
const uploadRef = ref(null);
const saveLoading = ref(false);
const submitLoading = ref(false);

watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
    if (val) {
      form.reportType = props.defaultType;
      form.reportName = props.defaultName;
      file.value = null;
    }
  }
);
watch(
  () => visible.value,
  (val) => {
    emit("update:modelValue", val);
  }
);

const handleFileChange = (f) => {
  file.value = f;
  if (f && f.name) {
    const base = f.name.replace(/\.(xlsx|xls)$/i, "");
    form.reportName = `${base} ${form.reportType}`;
  }
};
const handleFileRemove = () => {
  file.value = null;
  form.reportName = "";
};
const handleCancel = () => {
  visible.value = false;
  emit("cancel");
};
const handleSave = async () => {
  if (!form.reportName) {
    ElMessage.warning("请输入报告名称");
    return;
  }
  if (!file.value) {
    ElMessage.warning("请上传EXCEL文件");
    return;
  }
  saveLoading.value = true;
  try {
    const formData = new FormData();
    formData.append("file", file.value.raw || file.value);
    const res = await saveReport(formData, form.reportType, form.reportName);
    if (res.code === 200) {
      ElMessage.success("导入数据中，请稍后到列表生成报告");
      visible.value = false;
      emit("submit", res.data);
    } else {
      ElMessage.error(res.msg || "暂存失败");
    }
  } catch (e) {
    ElMessage.error("网络异常，请稍后重试");
  } finally {
    saveLoading.value = false;
  }
};

const handleSubmit = async () => {
  if (!form.reportName) {
    ElMessage.warning("请输入报告名称");
    return;
  }
  if (!file.value) {
    ElMessage.warning("请上传EXCEL文件");
    return;
  }
  submitLoading.value = true;
  try {
    const formData = new FormData();
    formData.append("file", file.value.raw || file.value);
    let res;
    if (form.reportType === "周报") {
      res = await generateWeekReport(
        formData,
        form.reportType,
        form.reportName
      );
    } else if (form.reportType === "月报") {
      res = await generateMonthReport(
        formData,
        form.reportType,
        form.reportName
      );
    } else {
      ElMessage.error("未知的报告类型");
      submitLoading.value = false;
      return;
    }
    if (res.code === 200) {
      ElMessage.success("报告生成成功");
      visible.value = false;
      emit("submit", res.data);
    } else {
      ElMessage.error(res.msg || "报告生成失败");
    }
  } catch (e) {
    ElMessage.error("网络异常，请稍后重试");
  } finally {
    submitLoading.value = false;
  }
};
const resetDialog = () => {
  form.reportType = props.defaultType;
  form.reportName = props.defaultName;
  file.value = null;
};
</script>

<style lang="scss" scoped>
.generate-form {
  .type-row .el-form-item__content {
    align-items: center;
  }
  .upload-row .el-form-item__content {
    flex-direction: column;
    align-items: flex-start;
  }
  .name-row .el-form-item__content {
    align-items: center;
    position: relative;
  }
}
.custom-upload {
  width: 420px;
  height: 180px;
  border: 2px dashed #409eff;
  border-radius: 8px;
  background: #fafcff;
  margin-bottom: 8px;
  .upload-inner {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .upload-icon {
      font-size: 56px;
      color: #409eff;
      margin-bottom: 8px;
    }
    .upload-text {
      color: #606266;
      font-size: 15px;
    }
  }
}
.file-info-bar {
  display: flex;
  align-items: center;
  margin-top: 6px;
  .file-clip {
    color: #bfbfbf;
    font-size: 16px;
  }
  .file-name {
    margin-left: 4px;
    font-size: 14px;
    color: #606266;
  }
  .file-close {
    color: #bfbfbf;
    font-size: 16px;
    margin-left: 4px;
  }
}
.generate-tip {
  color: #faad14;
  background: #fffbe6;
  padding: 2px 10px;
  border-radius: 4px;
  font-size: 13px;
  margin-left: 12px;
  display: inline-block;
  position: absolute;
  right: -210px;
  top: 0;
  white-space: nowrap;
}
.tip-float {
  position: absolute;
  right: 32px;
  top: 340px;
  color: #faad14;
  background: #fffbe6;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 13px;
  z-index: 10;
  box-shadow: 0 2px 8px #eee;
  white-space: nowrap;
}
.footer-btns {
  display: flex;
  justify-content: center;
  gap: 32px;
}

:deep(.el-form-item__content) {
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
}

:deep(.file-info-bar) {
  width: 100%;
}

:deep(.el-progress) {
  display: flex !important;
}

:deep(.el-upload-dragger) {
  border: none;
}

:deep(.upload-demo) {
  width: 500px;
}
</style>
